import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken } from '@/utils/auth'
import { Notify } from 'vant'
NProgress.configure({ showSpinner: false })
// 根据下钻改变title
const pathDownChangeTitleList = ['/collegeMsg', '/gradeMsg', '/instructorMsg', '/classesListMsg', '/warningList']

const whiteList = ['/login']
const getRole = localStorage.getItem('roleCode') || 'noAccess'
router.beforeEach(async (to, from, next) => {
  // 根据权限跳转改变title
  if (to.path === '/counsellor') {
    // to.meta.title = '8'
  }
  // 根据下钻改变title
  if (pathDownChangeTitleList.includes(to.path) && to.query.tc) {
    to.meta.title = to.query.tc
  }

  const hasToken = getToken()
  // 上课啦跳转登陆两个页面
  const isSklLogin = ['/warningStu', '/fiveHard'].includes(to.path) && to.query.token
  NProgress.start()
  if (whiteList.indexOf(to.path) !== -1 || isSklLogin) {
    if (isSklLogin) {
      const token = `Bearer ${to.query.token}`
      setToken(token)
    }
    next()
  } else {
    if (hasToken) {
      if (to.meta.auth && to.meta.auth.indexOf(getRole) === -1) {
        next(from.path)
        Notify({ type: 'danger', message: '没有权限!' })
        NProgress.done()
      } else if (!to.meta.auth && to.name) {
        next()
      } else if (!to.name) {
        next(`/404?redirect=${to.path}`)
      } else {
        next()
      }
    } else if (!hasToken) {
      next(`/login`)
      NProgress.done()
    }
  }
})
router.afterEach(to => {
  NProgress.done()
})
